<template>
  <div>
    <el-input :placeholder="placeholder" v-model="showValue" class="input-with-select" disabled :clearable="clearable">
      <el-button slot="append" @click="handleOpenDialog">{{ btnText }}</el-button>
    </el-input>
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form
        :model="queryParams"
        @submit.native.prevent
        ref="queryForm"
        size="small"
        :inline="true"
        class="clearfix"
        label-width="auto"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" :height="height" :data="options" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" v-if="multiple" />
        <el-table-column v-else width="30">
          <template slot-scope="scope">
            <el-radio :label="`${scope.row[defaultProps.value]}`" v-model="selectValue" @input="handleCheckedChange">{{
              ''
            }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column
          :label="item.label"
          align="center"
          :prop="item.prop"
          :key="index"
          v-for="(item, index) in column"
        >
          <template slot-scope="scope">
            <dict-tag v-if="item.dictName" :options="dicts[item.dictName]" :value="scope.row[item.prop]" />
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="optionsQueryParams.pageNum"
        :limit.sync="optionsQueryParams.pageSize"
        :page-size.sync="optionsQueryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TableSelect',
  props: {
    value: [Object, Array],
    // 树结构数据
    request: {
      type: Function,
    },
    optionData: {
      type: Array,
      default() {
        return []
      },
    },
    dicts: {
      type: Object,
      default() {
        return {}
      },
    },
    column: {
      type: Array,
      default() {
        return []
      },
    },
    // 配置是否可多选
    multiple: {
      type: Boolean,
      default() {
        return false
      },
    },
    // 配置是否开启二次确认弹框
    secondConfirm: {
      type: Boolean,
      default() {
        return false
      },
    },
    // 配置是否开启二次确认弹框
    confirmTitle: {
      type: String,
      default() {
        return '是否确认执行此操作?'
      },
    },
    // 配置是否返回整行数据
    isReturnRow: {
      type: Boolean,
      default() {
        return false
      },
    },
    // 开启二次确认弹框判断表达式
    judgmentExpression: {
      type: Function,
      default: function (selectRow) {
        console.log('selectRow', selectRow)
        return true
      },
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    title: {
      type: String,
      default: '选项',
    },
    btnText: {
      type: String,
      default: '选择',
    },
    // 配置是否可清空选择
    clearable: {
      type: Boolean,
      default() {
        return true
      },
    },
    max: {
      type: String,
      default() {
        return 'small'
      },
    },
    height: {
      type: Number,
      default() {
        return 400
      },
    },
    queryParams: {
      type: Object,
      default() {
        return {}
      },
    },
    defaultProps: {
      type: Object,
      default() {
        return { label: 'label', value: 'value' }
      },
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      open: false,
      // 总条数
      total: 0,
      options: [],
      // 查询参数
      optionsQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
      },
      selectRow: {},
      selectValue: null,
      selectLabel: '',
      selectValues: [],
      selectLabels: [],
      selectData: [],
      showValue: '',
    }
  },
  created() {
    this.column.forEach((item) => {
      if (item.isLabel) {
        this.defaultProps.label = item.prop
      } else if (item.isValue) {
        this.defaultProps.value = item.prop
      }
    })
    this.updateValue(this.value)
  },
  watch: {
    value: {
      deep: true,
      handler(val) {
        this.updateValue(val)
      },
    },
  },
  methods: {
    updateValue(val) {
      if (val) {
        if (Array.isArray(val)) {
          this.selectValues = this.selectData.map((k) => k[this.defaultProps.value]) || []
          this.selectLabels = this.selectData.map((k) => k[this.defaultProps.label]) || []
          this.showValue = this.selectLabels.join(',')
        } else {
          this.selectValue = val[this.defaultProps.value] || ''
          this.selectLabel = val[this.defaultProps.label] || ''
          this.showValue = this.selectLabel
        }
      } else {
        this.selectValue = null
        this.selectLabel = ''
        this.selectValues = []
        this.selectLabels = []
        this.showValue = ''
      }
    },
    handleOpenDialog() {
      this.optionsQueryParams = {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
      }
      if (Array.isArray(this.value)) {
        this.selectData = this.value.map((item, index) => {
          let option = {}
          option[this.defaultProps.value] = item
          option[this.defaultProps.label] = this.selectLabels[index]
          return option
        })
      } else if (this.value) {
        const arr = [JSON.parse(JSON.stringify(this.value))]
        this.selectData = arr
      }

      this.getList()
      this.open = true
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.optionsQueryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    getList() {
      this.loading = true
      if (this.request) {
        this.request(this.addDateRange({ ...this.optionsQueryParams, ...this.queryParams })).then((response) => {
          this.options = response.rows
          this.total = response.total
          this.loading = false
          let selectedUserDate = []
          let value = this.defaultProps.value
          this.options.forEach((row) => {
            let index = this.selectData.findIndex((item) => {
              return item[value] == row[value]
            })
            if (index >= 0) {
              selectedUserDate.push(row)
            }
          })

          this.$nextTick(() => {
            selectedUserDate.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row)
            })
          })
        })
      } else {
        this.options = this.optionData.slice(
          (this.optionsQueryParams.pageNum - 1) * this.optionsQueryParams.pageSize,
          this.optionsQueryParams.pageNum * this.optionsQueryParams.pageSize
        )
        this.total = this.optionData.length
        this.loading = false
      }
    },
    handleSelectionChange(selection) {
      let value = this.defaultProps.value
      this.options.forEach((row) => {
        let index = this.selectData.findIndex((option) => {
          return option[value] == row[value]
        })
        if (index >= 0) {
          this.selectData.splice(index, 1)
        }
      })
      this.selectData = this.selectData.concat(selection)
    },
    handleCheckedChange(selectValue) {
      let index = this.options.findIndex((option) => {
        return option[this.defaultProps.value] == selectValue
      })
      let selected = this.options[index]
      this.selectRow = this.options[index]
      this.selectLabel = selected[this.defaultProps.label]
    },
    handleConfirm() {
      let selectData = this.selectData.map((item, index) => {
        item[this.defaultProps.value] = item[this.defaultProps.value]
        item[this.defaultProps.label] = item[this.defaultProps.label]
        return item
      })
      if (this.multiple) {
        this.$emit('change', selectData)
        this.$emit('input', selectData)
      } else {
        if (this.secondConfirm && this.judgmentExpression(this.selectRow)) {
          this.$confirm(this.confirmTitle ? this.confirmTitle : '是否确定执行此操作?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(function () {
              //todo
            })
            .catch(() => {
              this.showValue = null
              this.selectRow = null
              this.selectLabel = null
              return
            })
        }
        let result = {}
        result[this.defaultProps.value] = this.selectValue
        result[this.defaultProps.label] = this.selectLabel
        this.$emit('change', { ...this.selectRow, ...result })
        this.$emit('input', result)
        if (this.isReturnRow) {
          this.$emit('returnRow', this.selectRow)
        }
      }
      this.open = false
    },
    cancel() {
      this.open = false
      this.selectValue = this.value.id
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-input.is-disabled {
  .el-input__inner {
    color: #323233;
    background-color: #fff;
  }
}
</style>
